package com.weme.common.base

import android.content.Context
import android.content.res.Resources
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.os.IBinder
import android.view.*
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.weme.common.controller.FloatingWindowController
import io.agora.chat.BuildConfig
import me.jessyan.autosize.AutoSizeConfig
import me.jessyan.autosize.internal.CustomAdapt
import me.jessyan.autosize.utils.ScreenUtils
import java.lang.reflect.ParameterizedType


abstract class BaseMvvmActivity<VB : ViewBinding, VM : BaseViewModel> : AppCompatActivity(), CustomAdapt {
    protected lateinit var viewModel: VM
    protected lateinit var mBinding: VB
    var surfaceView: SurfaceView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (BuildConfig.DEBUG) {
            window.setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE)
        }
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)

        viewModel = ViewModelProvider(this).get(getViewModelClass())
        val type = javaClass.genericSuperclass
        if (type is ParameterizedType) {/*例如 这里的 clz为 class cn.dfordog.basicviewbind.databinding.ActivityMainBinding*//*getActualTypeArguments获取参数化类型的数组，泛型可能有多个 此处就一个 ViewBinding*/
            val clz = type.actualTypeArguments[0] as Class<*>/*通过反射获取该类下的 inflate 方法*/
            val method = clz.getMethod("inflate", LayoutInflater::class.java)
            mBinding = method.invoke(null, layoutInflater) as VB
            setContentView(mBinding.root)
        }
        initView(savedInstanceState)
       // setTransparentStatusBar(window)
        ImmersionBar.with(this).hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR).init()

    }




    override fun isBaseOnWidth(): Boolean {
        return true
    }

    override fun getSizeInDp(): Float {
        return 360.0F
    }

    override fun onResume() {
        super.onResume()
        surfaceView?.apply {
            val rootView = window.decorView.findViewById<ViewGroup>(android.R.id.content).getChildAt(0) as ViewGroup
            FloatingWindowController.showFloatingWindow(rootView, surfaceView = this)
        }


    }





    protected abstract fun initView(savedInstanceState: Bundle?)
    protected abstract fun getViewModelClass(): Class<VM>


    open fun needHideCursor(): EditText? = null


    open fun getNavigationBarHeight(context: Context): Int {
        val resources: Resources = context.resources
        val resourceId: Int = resources.getIdentifier("navigation_bar_height", "dimen", "android")
        return if (resourceId > 0) {
            resources.getDimensionPixelSize(resourceId)
        } else 0
    } //    open fun getNavigationBarHeight(context: Context): Int { //        val resources = context.resources

    //        val resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android")
    //        if (resourceId > 0) {
    //            val navigationBarHeight = resources.getDimensionPixelSize(resourceId)
    //
    //            // 获取屏幕高度
    //            val displayMetrics = resources.displayMetrics
    //            val screenHeight = displayMetrics.heightPixels
    //
    //            // 计算虚拟按键距离屏幕底部的高度
    //            return screenHeight - navigationBarHeight
    //        }
    //        return 0 // 如果没有虚拟按键，返回 0
    //    }
    fun setScreenWidthHeight() { //适配用的
        val screenSize = ScreenUtils.getScreenSize(applicationContext)
        val width = screenSize[0]
        val height = screenSize[1]
        AutoSizeConfig.getInstance().screenWidth = width
        AutoSizeConfig.getInstance().screenHeight = height
    }

    var enableHideSoftInput = true

    /**
     * 点击空白处 将软键盘隐藏
     */
    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        if (enableHideSoftInput) {
            if (ev?.action == MotionEvent.ACTION_DOWN) {
                val view = currentFocus
                if (isShouldHideKeyBord(view, ev)) {

                    hideSoftInput(view?.windowToken)

                }
            }

            return super.dispatchTouchEvent(ev)
        } else {
            return super.dispatchTouchEvent(ev)
        }


    }

    /**
     * 判定当前是否需要隐藏
     */
    private fun isShouldHideKeyBord(v: View?, ev: MotionEvent): Boolean {
        if (v != null && v is EditText) {
            val l = intArrayOf(0, 0)
            v.getLocationInWindow(l)
            val left = l[0]
            val top = l[1]
            val bottom: Int = top + v.getHeight()
            val right: Int = left + v.getWidth()
            return !(ev.x > left && ev.x < right && ev.y > top && ev.y < bottom)
        }
        return false
    }

    /**
     * 隐藏软键盘
     */
    protected fun hideSoftInput(token: IBinder?) {
        if (token != null) {
            val manager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            manager.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        viewModel.onCleared()
    }
}
